package com.example.zg.androidnewview;

import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextInputLayout textInputLayout;
    private EditText editText;
    private EditText editText3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        init();

    }


    private void initView(){
        textInputLayout=findViewById(R.id.textInputLayout1);
        editText=findViewById(R.id.editText1);
        editText3=findViewById(R.id.editText3);

    }

    private void init(){
        //设置错误文字提示的样式
        textInputLayout.setErrorTextAppearance(R.style.error);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i(TAG, "onTextChanged: s="+s);
                if(s.toString().contains(" ")){
                    textInputLayout.setErrorEnabled(true);//显示错误提示
                    textInputLayout.setError("不能输入空格");//错误文字类容
                }else {
                    textInputLayout.setErrorEnabled(false);//关闭错误提示
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        editText3.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                switch (actionId){
                    case EditorInfo.IME_ACTION_SEARCH:
                        Toast.makeText(MainActivity.this, "搜索", Toast.LENGTH_SHORT).show();
                        break;
                }

                return false;
            }
        });
    }

}
